<?php

namespace app\api\controller\mycurrency;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\acc\BedOrder;
use app\common\model\billiard\StoreGoods;
use app\common\model\mycurrency\Device;
use app\common\model\mycurrency\DeviceLattice;
use app\common\model\mycurrency\MerchantStoreEvaluate;
use fast\Random;
use Psr\Log\NullLogger;
use think\Config;
use think\Exception;
use think\Validate;
use think\Db;
use addons\mycurrency\library\Common;

/**
 * 商铺接口
 */
class MerchantStore extends Api
{
    protected $noNeedLogin = ['storeList','storeInfo','storeDeviceList','storeDeviceGoodsList','storeDeviceGoodsInfo','storeEvaluateList','deviceGetStore','storeDeviceLatticeList','storeDeviceLatticeInfo'];
    protected $noNeedRight = '*';
    protected $agent = null;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 门店列表
     */
    public function storeList(){
        $param = $this->request->param();
        $rule = [
            ['page', 'require|>:0', '请填写当前页|当前页展示数量必须大于0'],
            ['pageSize', 'require|>:0', '请填写每页展示数量|每页展示数量必须大于0'],
            //['lat', 'require', '请填写维度'],
            //['lng', 'require', '请填写经度'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'status' => \app\common\model\mycurrency\MerchantStore::STATUS_ZHENGCHENG,
            'deletetime' => null,
        ];
        $lat=$param['lat'];
        $lng=$param['lng'];
        $field = [
            'id',
            'store_name',
            'dorrhead_image',
            'address',
            'longitude',
            'latitude',
            'status',
            //"ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$lat} * PI() / 180 - latitude * PI() / 180) / 2), 2)+ COS({$lat} * PI() / 180) * COS(latitude * PI() / 180)* POW(SIN(( {$lng} * PI() / 180 - longitude * PI() / 180 ) / 2),2))),2)" => 'distance',
        ];
        if($param['lat'] != null && $param['lng'] != null){
            $field[ "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$lat} * PI() / 180 - latitude * PI() / 180) / 2), 2)+ COS({$lat} * PI() / 180) * COS(latitude * PI() / 180)* POW(SIN(( {$lng} * PI() / 180 - longitude * PI() / 180 ) / 2),2))),2)"] = 'distance';
            $order = 'distance asc,id desc';
        }else{
            $order = 'id desc';
        }
        $list = \app\common\model\mycurrency\MerchantStore::where($where)->limit(($param['page'] - 1) * $param['pageSize'], $param['pageSize'])->field($field)->order($order)->select();
        if($param['lat'] == null && $param['lng'] == null){
            foreach($list as $k => $v){
                $list[$k]['distance'] = '';
            }
        }
        $num = \app\common\model\mycurrency\MerchantStore::where($where)->count();
        if ($num > $param['page'] * $param['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('',[
            'list' => $list,
            'nextpage' => $nextpage,
        ]);
    }

    /**
     * 门店详情
    */
    public function storeInfo(){
        $param = $this->request->param();
        $rule = [
            ['store_id', 'require', '门店id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $evaluate_pageSize = 5;//评论查询条数
        if($param['lat'] == null || $param['lng'] == null){
            $field = '*';
        }else{
            $lat=$param['lat'];
            $lng=$param['lng'];
            $field = [
                'id',
                'merchant_id',
                'store_name',
                'dorrhead_image',
                'album_images',
                'province_id',
                'city_id',
                'area_id',
                'address',
                'longitude',
                'latitude',
                'fullname',
                'phone',
                'money',
                'score',
                'status',
                'createtime',
                'updatetime',
                "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$lat} * PI() / 180 - latitude * PI() / 180) / 2), 2)+ COS({$lat} * PI() / 180) * COS(latitude * PI() / 180)* POW(SIN(( {$lng} * PI() / 180 - longitude * PI() / 180 ) / 2),2))),2)" => 'distance',
            ];
        }

        $data = \app\common\model\mycurrency\MerchantStore::with(['evaluate' => function($query)use($evaluate_pageSize){
            $query->where([
                'display_status' => MerchantStoreEvaluate::DISPLAY_STATUS_XIANSHI,
                'deletetime' => null,
            ]);
            $query->limit((1 - 1) * $evaluate_pageSize, $evaluate_pageSize);
            $query->with(['user' => function($query){
                $query->field('id,nickname,avatar');
            }]);
        }])->where(['id' => $param['store_id']])->field($field)->find();
        if($param['lat'] == null || $param['lng'] == null){
            $data['distance'] = null;
        }
        if(!$data){
            $this->error('门店不存在');
        }
        $this->success('',$data);
    }


    /**
     * 门店 = 台球柜列表
    */
    public function storeDeviceList(){
        $param = $this->request->param();
        $rule = [
            ['store_id', 'require', '门店id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'store_id' => $param['store_id'],
            'status' => Device::STATUS_ZHENGCHENG,
            'is_fault' => Device::IS_FAULT_WU,
            'is_online' => Device::IS_ONLINE_ZAIXIAN,
            'deletetime' => null,
        ];
        $data = Device::where($where)->field('id,number,title')->select();
        if(!$data){
            $this->error('无可用台球柜');
        }
        $this->success('加载成功',$data);
    }

    /**
     * 门店 = 台球柜 = 台球杆列表
     */
    public function storeDeviceGoodsList(){
        $param = $this->request->param();
        $rule = [
            ['device_id', 'require', '台球柜id不能为空'],
            ['store_id', 'require', '门店id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $device_ids = Device::where(['store_id' => $param['store_id']])->column('id');
        $device_id = $param['device_id'];
        $device_number = Device::where(['id' => $device_id])->value('number');
        $store_goods_ids = DeviceLattice::where([
            'device_id' => $param['device_id'],
            'status' => DeviceLattice::STATUS_ZHENGCHENG,
            'is_fault' => DeviceLattice::IS_FAULT_WU,
            'deletetime' => null,
        ])->distinct(true)->column('store_goods_id');
        $where = [
            'store_id' => $param['store_id'],
            'id' => ['in',$store_goods_ids],
            'deletetime' => null,
        ];
//        print_r($where);die();
        $data = StoreGoods::with(['strategy','goods'])
            ->withCount(['goodsAssemble' => function($query) use($device_id){
                $query->where([
                    'device_id' => $device_id,
                    'status' => DeviceLattice::STATUS_ZHENGCHENG,
                    'is_fault' => DeviceLattice::IS_FAULT_WU,
                    'deletetime' => null,
                ]);
            }])
            ->withCount(['goodsAvailable' => function($query) use($device_id){
                $query->where([
                    'device_id' => $device_id,
                    'status' => DeviceLattice::STATUS_ZHENGCHENG,
                    'use_status' => DeviceLattice::USE_STATUS_YOUGAN,
                    'is_fault' => DeviceLattice::IS_FAULT_WU,
                    'deletetime' => null,
                ]);
            }])
            ->where($where)
            ->order('id desc')
            ->select();
        foreach($data as $k => $v){
            $data[$k]['device_number'] = $device_number;
            $data[$k]['goods']['abbreviation_image'] = Common::GetHost() . $data[$k]['goods']['abbreviation_image'];
            $data[$k]['device_id'] = $param['device_id'];
        }
        $this->success('加载成功',$data);
    }

    /**
     * 门店 = 台球柜 = 台球杆 = 台球杆详情
    */
    public function storeDeviceGoodsInfo(){
        $param = $this->request->param();
        $rule = [
            ['device_id', 'require', '台球柜id不能为空'],
            ['store_goods_id', 'require', '产品id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $device_id = $param['device_id'];
        $device_number = Device::where(['id' => $device_id])->value('number');
        $where = [
            'id' => $param['store_goods_id'],
            'deletetime' => null,
        ];
        $data = StoreGoods::with(['strategy','goods'])
            ->withCount(['goodsAssemble' => function($query) use($device_id){
                $query->where([
                    'device_id' => $device_id,
                    'deletetime' => null,
                ]);
            }])
            ->withCount(['goodsAvailable' => function($query) use($device_id){
                $query->where([
                    'device_id' => $device_id,
                    'status' => DeviceLattice::STATUS_ZHENGCHENG,
                    'use_status' => DeviceLattice::USE_STATUS_YOUGAN,
                    'is_fault' => DeviceLattice::IS_FAULT_WU,
                    'deletetime' => null,
                ]);
            }])
            ->where($where)
            ->find();
        $data['device_number'] = $device_number;
        $data['goods']['abbreviation_image'] = Common::GetHost() . $data['goods']['abbreviation_image'];
        if(!$data){

            $this->error('产品不存在');
        }
        $this->success('加载成功',$data);
    }


    /**
     * 门店 - 评价记录列表
     */
    public function storeEvaluateList(){
        $param = $this->request->param();
        $rule = [
            ['store_id', 'require', '门店id不能为空'],
            ['page', 'require|>:0', '请填写当前页|当前页展示数量必须大于0'],
            ['pageSize', 'require|>:0', '请填写每页展示数量|每页展示数量必须大于0'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'store_id' => $param['store_id'],
            'display_status' => MerchantStoreEvaluate::DISPLAY_STATUS_XIANSHI,
            'deletetime' => null,
        ];
        $field = '*';
        $order = 'id desc';
        $list = MerchantStoreEvaluate::with(['user' => function($query){
            $query->field('id,nickname,avatar');
        }])->where($where)->limit(($param['page'] - 1) * $param['pageSize'], $param['pageSize'])->field($field)->order($order)->select();
        $num = MerchantStoreEvaluate::where($where)->count();
        if ($num > $param['page'] * $param['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('',[
            'list' => $list,
            'nextpage' => $nextpage,
        ]);
    }

    /**
     * 评价 - 用户发布评价
    */
    public function userEvaluateStore(){
        $param = $this->request->param();
        $rule = [
            ['store_id', 'require', '门店id不能为空'],
            ['score', 'require|>:0', '评分不能为空|评分必须大于0'],
            ['content', 'require', '评价内容不能为空'],
            ['picture_images', 'require', '评价图片不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $store = \app\common\model\mycurrency\MerchantStore::get($param['store_id']);
        if(!$store){
            $this->error('门店不存在');
        }
        Db::startTrans();
        try {
            //添加评价记录
            $increase = [
                'store_id' => $param['store_id'],
                'user_id' => $this->auth->id,
                'score' => $param['score'],
                'content' => $param['content'],
                'picture_images' =>$param['picture_images'],
                'display_status' => MerchantStoreEvaluate::DISPLAY_STATUS_YINCANG,
                'createtime' => time(),
            ];
            MerchantStoreEvaluate::create($increase);

            //更新平均评分
            $avg = MerchantStoreEvaluate::where(['store_id' => $param['store_id']])->avg('score');
            \app\common\model\mycurrency\MerchantStore::where(['id' => $param['store_id']])->update([
                'score' => $avg,
            ]);
            Db::commit();
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('发布成功');
    }

    /**
     * 根据设备编号 查询门店id 及设备id
    */
    public function deviceGetStore(){
        $param = $this->request->param();
        $rule = [
            ['number', 'require', '设备编号不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $device = Device::where(['number' => $param['number'],'deletetime' => null])->find();
        if (!$device){
            $this->error('设备不存在');
        }
        if($device['status'] == Device::STATUS_JINYONG){
            $this->error('设备被禁用');
        }
        if($device['is_fault'] == Device::IS_FAULT_YOU){
            $this->error('设备存在故障');
        }
        if($device['is_online'] == Device::IS_ONLINE_BUZAIXIAN){
            $this->error('设备离线');
        }
        if($device['store_id'] == null){
            $this->error('设备未绑定店铺');
        }
        $this->success('',[
            'device_id' => $device->id,
            'store_id' => $device->store_id,
        ]);
    }

    /**
     * 门店 = 台球柜 = 柜门列表
    */
    public function storeDeviceLatticeList(){
        $param = $this->request->param();
        $rule = [
            ['device_id', 'require', '台球柜id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'device_id' => $param['device_id'],
            'status' => DeviceLattice::STATUS_ZHENGCHENG,
            'is_fault' => DeviceLattice::IS_FAULT_WU,
            'deletetime' => null,
            'store_goods_id' => ['not in',null],
        ];
        $data = DeviceLattice::with(['storeGoods' => function($query){
                $query->with(['goods' => function($query){
                    $query->field('id,title,abbreviation_image');
                },'strategy' => function($query){
                    $query->field('id,title,types,unit_price,duration');
                }]);
                $query->field('id,lease_strategy_id,goods_id,advance_fee');
            }])
            ->where($where)
            ->order('number asc,id desc')
            ->field('id,number,use_status,store_goods_id')
            ->select();
        foreach($data as $k => $v){
            $data[$k]['advance_fee'] = $data[$k]['store_goods']['advance_fee'];//预付金
            $data[$k]['goods_title'] = $data[$k]['store_goods']['goods']['title'];//产品标题
            $data[$k]['goods_abbreviation_image'] = Common::GetHost() . $data[$k]['store_goods']['goods']['abbreviation_image'];//产品图片

            $data[$k]['unit_price'] = $data[$k]['store_goods']['strategy']['unit_price'];//时长
            $data[$k]['duration'] = $data[$k]['store_goods']['strategy']['duration'];//价格
            $data[$k]['charge_text'] = $data[$k]['store_goods']['strategy']['charge_text'];//收费信息
            unset($data[$k]['store_goods']);
        }
        $this->success('加载成功',$data);
    }

    /**
     * 门店 = 台球柜 = 柜门详情
     */
    public function storeDeviceLatticeInfo(){
        $param = $this->request->param();
        $rule = [
            ['device_lattice_id', 'require', '台球柜柜门id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'id' => $param['device_lattice_id'],
            'deletetime' => null,
        ];
        $data = DeviceLattice::with(['storeGoods' => function($query){
                $query->with(['goods','strategy']);
            }])
            ->where($where)
            ->find();

        $data['advance_fee'] = $data['store_goods']['advance_fee'];//预付金
        $data['goods_title'] = $data['store_goods']['goods']['title'];//产品标题
        $data['goods_abbreviation_image'] = Common::GetHost() . $data['store_goods']['goods']['abbreviation_image'];//产品图片
        $data['goods_album_images'] = $data['store_goods']['goods']['album_images'];//产品相册
        $data['goods_details'] = $data['store_goods']['goods']['details'];//产品详情

        $data['unit_price'] = $data['store_goods']['strategy']['unit_price'];//时长
        $data['duration'] = $data['store_goods']['strategy']['duration'];//价格
        $data['charge_text'] = $data['store_goods']['strategy']['charge_text'];//收费信息
        unset($data['store_goods']);
        //产品缩略图 产品标题 使用状态 收费 预付金 产品详情
        if(!$data){
            $this->error('柜门不存在');
        }
        $this->success('加载成功',$data);
    }

}
